import BaseSprite from "../../../Script/Base/BaseSprite";
import EventID from "../../../Script/Common/EventID";
import { IMessage, IStoreData } from "../../../Script/Interface/IMessage";
import StoreItem from "./StoreItem";
import StoreGuest from "./StoreGuest";
import StoreUI from "./StoreUI";
import BaseConfig from "../../Base/BaseConfig";
import GameUtil from "../../Util/GameUtil";
import StorageUtil from "../../Util/StorageUtil";

const { ccclass, property } = cc._decorator;

// 小卖店玩法---大厅
@ccclass
export default class Hall extends BaseSprite implements IMessage {

    @property({ type: cc.Node, tooltip: "" })
    private items: cc.Node = null;
    @property({ type: cc.Node, tooltip: "" })
    private item: cc.Node = null;

    @property({ type: cc.Node, tooltip: "顾客父节点" })
    private guests: cc.Node = null;
    @property({ type: cc.Node, tooltip: "顾客" })
    private itemGuest: cc.Node = null;

    private storeData: IStoreData = null;

    recvMsg(cmd: number, data: any) {
        switch (cmd) {
            case EventID.TEST_CMD:
                {

                }
                break;
        }
    }

    protected onLoad() {
        super.onLoad();
        this.addMessage(EventID.TEST_CMD, this);

        this.createGuest();
    }

    public refreshUI() {
        this.storeData = StorageUtil.instance.getStoreData();
        const datas = this.storeData.upItems;
        for (let i = 0; i < this.items.children.length; i++) {
            let node = this.items.children[i];
            let data = datas[i];
            if (!data) {
                datas.push({ counterId: i + 1, item: { id: -1, num: 0 } });
                data = datas[i];
            }
            if (data.item.id > -1) {
                let item = node.children[0];
                if (!item) {
                    item = cc.instantiate(this.item);
                    item.parent = node;
                }

                item.getComponent(StoreItem).setData('hall', data.item);
                // 数量不足销毁
                if (data.item.num <= 0) {
                    item.destroy();
                }
            }
        }
        // console.log('datas:', datas);
    }

    private createGuest() {
        const talkData = StorageUtil.instance.getTalkData();
        if (talkData.id <= 114)
            return;

        this.node.stopAllActions();
        cc.tween(this.node).repeatForever(
            cc.sequence(
                cc.callFunc(() => {
                    const datas = this.getSaleDatas();
                    const total = this.getTotalNum();
                    const guest = cc.instantiate(this.itemGuest);
                    guest.parent = this.guests;
                    guest.active = true;
                    guest.getComponent(StoreGuest).come({
                        isHad: total > 0,
                        refresh: () => {
                            datas?.forEach((o) => {
                                if (o?.item?.num > 0) {
                                    const index = o.counterId - 1;
                                    const counter = StoreUI.instance.getCounterItems();
                                    const node = counter.children[index].children[0];
                                    if (node) {
                                        o.item.num--;
                                        if (o.item.num <= 0) {
                                            node.destroy();
                                        } else {
                                            const comp = node.getComponent(StoreItem);
                                            comp.setData('up', o.item);
                                        }
                                    }
                                }
                            });
                            this.refreshUI();
                            StoreUI.instance.updateCounterInfo();
                        },
                        pay: () => {
                            datas?.forEach((o) => {
                                const config = BaseConfig.instance.getItemInfoById(o.item.id);
                                StoreUI.instance.refreshMoney(config.basePrice);
                            });
                        }
                    });
                }),
                cc.delayTime(Math.random() * 3 + 2),
            )
        ).start();
    }

    private getSaleDatas() {
        const datas = this.storeData.upItems;
        const filter = datas.filter((o) => o.item.num > 0);
        if (filter.length > 0) {
            const sales = [];
            const random = GameUtil.getRandomInteger(1, 5);
            for (let i = 0; i < random; i++) {
                const data = filter[Math.floor(Math.random() * filter.length)];
                if (data) {
                    sales.push(data);
                }
            }
            // console.log("卖出数据：", sales);
            return sales;
        }
        return null;
    }

    private getTotalNum() {
        let total = 0;
        let upItems = this.storeData.upItems;
        upItems.forEach((o) => {
            total += o.item.num;
        });
        return total;
    }

    private onBtnsClicked(event: cc.Event.EventTouch, eventData: string) {
        const name = event.target.name;
        switch (name) {
            case 'btnCounter':
                {
                    StoreUI.instance.openOtherNode(1);
                }
                break;
        }
    }
}